package org.yxj.requestlibaray.activity;

import androidx.annotation.Nullable;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jbh.permissionlibrary.PermissionManager;
import com.jbh.permissionlibrary.base.BasePermissionActivity;
import com.jbh.permissionlibrary.i.CheckPermissionListener;
import com.jbh.permissionlibrary.i.PermissionRequestCode;

import org.yxj.pictureselectorlib.PictureSelector;
import org.yxj.pictureselectorlib.PictureSelectorDialog;
import org.yxj.pictureselectorlib.PictureSelectorListener;
import org.yxj.requestlib.i.BaseServer;
import org.yxj.requestlib.i.Callback;
import org.yxj.requestlib.i.UploadFileCallback;
import org.yxj.requestlibaray.i.Apis;
import org.yxj.requestlib.manager.uploadfile.FileUploadRequestManager;
import org.yxj.requestlib.manager.api.RequestManager;
import org.yxj.requestlibaray.bean.BaseConfig;
import org.yxj.requestlibaray.bean.MultipartBodyBean;
import org.yxj.requestlibaray.R;
import org.yxj.requestlibaray.bean.TokenResponse;
import org.yxj.requestlibaray.i.Api;
import org.yxj.requestlibaray.i.MeServer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MultipartBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends BasePermissionActivity implements PictureSelectorListener{

    private PictureSelector  pictureSelector ;
    private TextView btn_postImg ;
    private ProgressBar mProgressBar ;

    private Object object = new Object();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        getServerTimeTask();
//
//        mProgressBar = findViewById(R.id.mProgressBar);
//        pictureSelector = new PictureSelector();
//        pictureSelector.setListener(this);
//        pictureSelector.setSupportCrop(false);
//
//        btn_postImg = findViewById(R.id.btn_postImg);
//        btn_postImg.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                postImgTask();
//            }
//        });
//
//        findViewById(R.id.btn_fileList).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(MainActivity.this,UpLoadFileListActivity.class));
//            }
//        });
        tokenTask();
    }




    /**
     * 获取token
     *
     */
    public void tokenTask(){
        HashMap<String,Object> map = new HashMap<>() ;
        map.put("client_id","WeBo_Api_Client");
        map.put("client_secret","AQAAAAEAACcQAAAAEBSSX4Wced0APG5/f8p23Mb8gdi6dANjpLMO9I9dTBataXd4RXur7cFrMHoq4FxwJw==");
        map.put("grant_type","WeBo_Login_By_Password");
        map.put("mobile","15338895488");
        map.put("password","123qwe");
        map.put("appVersion","15.1");
        map.put("port","ios");

        Apis.newInstance().TokenTask(map, new Callback<TokenResponse>() {
            @Override
            public void onSuccess(TokenResponse tokenResponse) {
                String token = new StringBuffer()
                        .append(tokenResponse.token_type)
                        .append(" ")
                        .append(tokenResponse.access_token)
                        .toString();
                Log.v("[tokenTask]->","token = "+token);
                loginByPasswordTask(token);
                HomeGoodsList(token);
            }

            @Override
            public void onFail(int errorCode, String error) {
                Log.v("[tokenTask]->","onError = "+error);
            }
        });
    }
    /**
     * 获取列表数据
     * @param access_token
     */
    public void HomeGoodsList(String access_token){
        synchronized (object){
            HashMap<String,Object> map = new HashMap<>() ;
            map.put("SearchKey","");
            map.put("Page","1");
            map.put("PageSize","100");
            map.put("appVersion","15.1");
            map.put("port","ios");
            Apis.newInstance().authorization(access_token).HomeGoodsListTask(map, new Callback<Object>() {
                @Override
                public void onSuccess(Object tokenResponse) {
                    Log.v("[authorization]->=","token = "+new Gson().toJson(tokenResponse));
                }

                @Override
                public void onFail(int errorCode, String error) {
                    Log.v("[authorization]->=","onError = "+error);
                }
            });
        }
    }
    /**
     * 密码登录
     *
     * @param access_token
     */
    public void loginByPasswordTask(String access_token){
        synchronized (object){
            HashMap<String,Object> map = new HashMap<>() ;
            map.put("Mobile","15338895488");
            map.put("Password","123qwe");
            map.put("appVersion","15.1");
            map.put("port","ios");
            Apis.newInstance()
                    .authorization(access_token)
                    .LoginByPasswordTask(map, new Callback<Object>() {
                @Override
                public void onSuccess(Object o) {
                    Log.v("[loginByPasswordTask]->=","token = "+new Gson().toJson(o));
                }

                @Override
                public void onFail(int errorCode, String error) {
                    Log.v("[loginByPasswordTask]->=","onError = "+error);
                }
            });
        }
    }






    private void postImgTask() {
        new PictureSelectorDialog(this) {

            @Override
            public void setSelectorXC() {
                PermissionManager.newInstance().checkPermission(MainActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        PermissionRequestCode.WRITE_EXTERNAL_STORAGE_REQUEST_CODE
                        , new CheckPermissionListener() {
                            @Override
                            public void onNoNeedCheckPermission() {
                                pictureSelector.onPickPicture(MainActivity.this);
                            }
                        });
            }

            @Override
            public void setSelectorPZ() {
                List<String> list = new ArrayList<>();
                list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                list.add(Manifest.permission.CAMERA);
                PermissionManager.newInstance().checkPermission(MainActivity.this,
                        list,PermissionRequestCode.WRITE_EXTERNAL_STORAGE_AND_CAMERA_REQUEST_CODE,
                        new CheckPermissionListener() {
                            @Override
                            public void onNoNeedCheckPermission() {
                                /**
                                 * 参数二   拍照保存位置
                                 */
                                pictureSelector.onTakePhoto(MainActivity.this, Environment.getExternalStorageDirectory().getPath());
                            }
                        });
            }
        }.show();
    }





    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        pictureSelector.onActivityResult(this,requestCode,resultCode,data);
    }






    public void getServerTimeTask(){
        RequestManager.getInstance()
                .setAuthorization("测试授权")
                .init(Api.Host);
        HashMap<String,Object> map = new HashMap<>();
        map.put("Sex","变性人");
        BaseConfig builder = new BaseConfig.Builder()
                .setPostMap(map)
                .build();
        RequestManager.getInstance()
                .req(BaseServer.class)
                .api(Api.serverTime,builder.body())
                .subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.v("[ApiRequest]","onNext - > o = "+e.getMessage());
                    }

                    @Override
                    public void onNext(Object o) {
                        Log.v("[ApiRequest]","onNext - > o = "+new Gson().toJson(o));
                    }
                });
    }






    @Override
    public void onPictureSelectorResult(Object o) {
        postFileTask(o.toString());
    }






    /**
     * 使用 okHttp 实现图片上传
     *
     * @param realFilePath
     */
    private void postFileTask(String realFilePath) {
        MultipartBody.Builder body =  new MultipartBodyBean(realFilePath).build();
        FileUploadRequestManager.getInstance()
                .uploadFileByOkHttp(
                        "http://inte.zbs6.com/inte/interface.ashx/",
                        body, new UploadFileCallback<String>() {
                            @Override
                            public void progress(long total, long current) {
                                final float radio = (float) (current* 1.0 / total);
                                Log.v("[ApiRequest]","onNext - > progress   = "+ radio * 100);
                                mProgressBar.setProgress((int) (radio * 100));
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        btn_postImg.setText((int)(radio * 100)+"/%");
                                    }
                                });
                            }
                            @Override
                            public void success(String o) {
                                Log.v("[ApiRequest]","onNext - > success = "+o);
                                mProgressBar.setProgress(0);
                            }

                            @Override
                            public void failed(int code, String error) {
                                Log.v("[ApiRequest]","onNext - > error = "+error);
                            }
                        });
    }




}